<template>
  <div class="bg-white rounded-xl shadow-sm ring-1 ring-gray-200 p-5 hover:shadow-md transition">
    <div class="w-16 h-16 rounded-xl overflow-hidden mx-auto">
      <RobustImage 
        :src="image"
        :alt="name"
        class="w-full h-full object-cover rounded-xl"
        :fallback-text="name"
        :enable-retry="true"
        :max-retries="3"
      />
    </div>
    <div class="mt-3 text-center">
      <div class="text-gray-900 font-medium">{{ name }}</div>
      <div class="text-xs text-gray-500 mt-1 line-clamp-2">{{ intro }}</div>
    </div>
    <div class="mt-4 flex gap-2">
      <RouterLink :to="`/details/${id}`" class="flex-1 h-9 rounded-lg bg-[#635BFF] text-white text-sm flex items-center justify-center">
        开始对话
      </RouterLink>
      <button class="h-9 w-9 rounded-lg ring-1 ring-gray-200 text-gray-500 hover:bg-gray-50" @click="handlePlay">
        <svg class="h-4 w-4 mx-auto" fill="none" stroke="currentColor" viewBox="0 0 24 24">
          <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15.536 8.464a5 5 0 010 7.072m2.828-9.9a9 9 0 010 12.728M5.586 15H4a1 1 0 01-1-1v-4a1 1 0 011-1h1.586l4.707-4.707C10.923 4.663 12 5.109 12 6v12c0 .891-1.077 1.337-1.707.707L5.586 15z" />
        </svg>
      </button>
    </div>
  </div>
</template>

<script setup lang="ts">
import { characterInfo } from '@/api'
import { voicePlayerManager } from '@/utils/voicePlayerManager'

const props = defineProps<{ id: number | string; name: string; intro: string; image: string }>()

// 防抖标志
let isPlaying = false

async function handlePlay() {
  // 防止重复点击
  if (isPlaying) {
    return
  }

  try {
    isPlaying = true
    
    // 获取新的流式播放接口URL
    const streamUrl = characterInfo.voiceStreamPlay(props.id)
    
    // 使用全局播放器管理器
    await voicePlayerManager.play(streamUrl, {
      sampleRate: 22050,
      timeout: 30000,
      onStart: () => {
        
      },
      onEnd: () => {
        isPlaying = false
      },
      onError: (error) => {
        isPlaying = false
      }
    })
    
  } catch (e) {
    // 播放失败不阻断页面
    
    isPlaying = false
  }
}
</script>


